<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use App\Models\UserToken;
use App\Models\WechatUser;
use Carbon\Carbon;
use App\Models\VerificationCode;
use App\Models\Product;

/**
 * 验证码控制器
 * 用于处理微信小程序的验证码验证请求
 */
class VerifyCodeController extends Controller
{
    /**
     * 验证用户提供的验证码
     * 
     * 验证流程：
     * 1. 验证请求中是否包含必要的验证码
     * 2. 验证用户token是否有效
     * 3. 验证用户信息是否存在
     * 4. 验证验证码是否与存储的session_key匹配
     *
     * @param Request $request HTTP请求对象
     * @return \Illuminate\Http\JsonResponse 返回JSON格式的验证结果
     */
    public function verify(Request $request)
    {
        // 记录接收到的所有请求信息
        Log::info('收到验证请求', [
            'request_data' => $request->all(),
            'headers' => $request->header()
        ]);

        try {
            // 首先验证token
            $token = str_replace('Bearer ', '', $request->header('Authorization'));
            
            if (empty($token)) {
                Log::warning('验证失败：未提供token');
                return response()->json([
                    'valid' => false,
                    'message' => '请先登录',
                    'error_code' => 'TOKEN_MISSING'
                ], 200);
            }

            // 检查token是否存在且在有效期内
            $userToken = UserToken::where('token', $token)
                    ->where('expired_at', '>', Carbon::now())
                    ->first();

            if (!$userToken) {
                Log::warning('验证失败：token无效或已过期', [
                    'token' => $token
                ]);
                return response()->json([
                    'valid' => false,
                    'message' => 'token已过期，请重新登录',
                    'error_code' => 'TOKEN_INVALID'
                ], 200);
            }

            // 验证请求中必需的参数
            $validated = $request->validate([
                'code' => 'required|string'
            ]);

            // 1. 先查询验证码是否存在
            $verificationCode = VerificationCode::where('code', $validated['code'])->first();

            if (!$verificationCode) {
                Log::warning('验证码验证失败：验证码不存在', [
                    'code' => $validated['code']
                ]);
                return response()->json([
                    'valid' => false,
                    'message' => '验证码不存在',
                    'error_code' => 'CODE_NOT_FOUND'
                ], 200);
            }

            // 2. 检查验证码是否已被使用
            if ($verificationCode->is_used) {
                // 检查是否是当前用户使用的
                if ($verificationCode->wechat_user_id === $userToken->wechat_user_id) {
                    Log::info('验证码已被当前用户使用', [
                        'code' => $validated['code'],
                        'user_id' => $userToken->wechat_user_id,
                        'used_at' => $verificationCode->updated_at
                    ]);
                    return response()->json([
                        'valid' => false,
                        'message' => '该兑换码已经被您兑换，请查看我的订单',
                        'error_code' => 'CODE_USED_BY_SELF',
                        'redirect_to_order' => true  // 添加标记，提示前端跳转到订单页
                    ], 200);
                } else {
                    Log::warning('验证码验证失败：验证码已被其他用户使用', [
                        'code' => $validated['code'],
                        'current_user_id' => $userToken->wechat_user_id,
                        'used_by_user_id' => $verificationCode->wechat_user_id,
                        'used_at' => $verificationCode->updated_at
                    ]);
                    return response()->json([
                        'valid' => false,
                        'message' => '该兑换码已被使用',
                        'error_code' => 'CODE_USED_BY_OTHER'
                    ], 200);
                }
            }

            // 3. 检查验证码是否在有效期内
            if ($verificationCode->expired_at < Carbon::now()) {
                Log::warning('验证码验证失败：验证码已过期', [
                    'code' => $validated['code'],
                    'expired_at' => $verificationCode->expired_at
                ]);
                return response()->json([
                    'valid' => false,
                    'message' => '验证码已过期',
                    'error_code' => 'CODE_EXPIRED'
                ], 200);
            }

            // 获取商品信息
            $product = Product::find($verificationCode->product_id);

            // 验证通过，记录日志
            Log::info('验证码验证通过', [
                'user_id' => $userToken->wechat_user_id,
                'code' => $verificationCode->code,
                'product_name' => $product ? $product->name : 'unknown',
                'created_at' => $verificationCode->created_at,
                'expired_at' => $verificationCode->expired_at
            ]);

            // 返回验证成功的结果
            return response()->json([
                'valid' => true,
                'message' => '验证成功',
                'data' => [
                    'user_id' => $userToken->wechat_user_id,
                    'code' => $verificationCode->code,
                    'product_name' => $product ? $product->name : null,
                    'product_price' => $product ? $product->price : null,
                    'created_at' => $verificationCode->created_at,
                    'expired_at' => $verificationCode->expired_at
                ]
            ]);

        } catch (\Exception $e) {
            // 捕获并记录所有异常
            Log::error('验证过程发生异常', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            // 返回服务器错误响应
            return response()->json([
                'valid' => false,
                'message' => '服务器错误，请稍后重试',
                'error_code' => 'SERVER_ERROR'
            ], 200);
        }
    }
} 